<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket test1</title>
</head>
<body>
    <h3>
        WebSocket page for testing and pushing messages
    </h3>
    <br />
    <input id="text" type="text">&nbsp;&nbsp;
    <button onclick="send()">发送</button>
    &nbsp;&nbsp;&nbsp;
    <button onclick="close()">关闭</button>
    <br />
    <hr>
    <div id="message"></div>
</body>
</html>
<script>
    var webSocket = null;

    if ('WebSocket' in window) {
        webSocket = new WebSocket("ws://127.0.0.1:8080/websocket/1");
    } else {
        alert("此浏览器不支持websocket")
    }

    function setMessageInHtml(message) {
        document.getElementById("message").innerHTML += message;
    }

    webSocket.onopen = function () {
        console.log("发送成功");
        setMessageInHtml("on success")
    };

    // 点击发送按钮
    function send() {
        var message = document.getElementById("text").value;
        webSocket.send(message);
    }

    webSocket.onmessage = function (event) {
        setMessageInHtml(event.data);
    };

    // 断开连接调用的函数
    function close() {
        webSocket.close(3000, "强制关闭")
    }

    webSocket.onclose = function () {
        setMessageInHtml("close websocket");
    };

    window.onbeforeunload = function () {
        close();
    }

</script>